package com.wr.recruit.service.service.impl;

import com.sun.xml.internal.ws.api.message.Attachment;
import com.wr.recruit.service.dao.dbo.AttachmentDbo;
import com.wr.recruit.service.dao.dbo.CompanyDbo;
import com.wr.recruit.service.dao.dbo.UserDbo;
import com.wr.recruit.service.dao.repo.AttachmentRepo;
import com.wr.recruit.service.dao.repo.CompanyRepo;
import com.wr.recruit.service.dao.repo.UserRepo;
import com.wr.recruit.service.service.AttachmentService;
import com.wr.recruit.service.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

import static com.wr.recruit.service.utils.Constants.COMPANY_TYPE;

@Service
public class AttachmentServiceImpl implements AttachmentService {

    private AttachmentRepo attachmentRepo;
    private CompanyRepo companyRepo;
    private UserRepo userRepo;

    @Autowired
    public AttachmentServiceImpl(AttachmentRepo attachmentRepo,
                                 CompanyRepo companyRepo,
                                 UserRepo userRepo) {
        this.attachmentRepo = attachmentRepo;
        this.companyRepo = companyRepo;
        this.userRepo = userRepo;
    }

    @Value("${spring.uploadfile.location}")
    private String FILE_PATH ;

    @Override
    @Transactional
    public void store(String type, String code, MultipartFile file) throws Exception {
        String path = FILE_PATH + File.separator +  code + File.separator + file.getOriginalFilename();
        if(!new File(path).exists())
            FileUtils.createFile(path);

        try(FileOutputStream writer = new FileOutputStream(path)) {
            writer.write(file.getBytes());
        }catch (IOException e){
            throw new Exception();
        }
        String attachmentCode = UUID.randomUUID().toString();

        AttachmentDbo attachmentDbo = new AttachmentDbo();
        attachmentDbo.setAttachmentCode(attachmentCode);
        attachmentDbo.setFileName(file.getOriginalFilename());
        attachmentDbo.setFilePath(path);
        attachmentDbo.setUploadedDateTime(new Timestamp(new Date().getTime()));
        attachmentRepo.save(attachmentDbo);

        if (COMPANY_TYPE.equals(type)) {
            CompanyDbo allByCompanyCode = companyRepo.findAllByCompanyCode(code);
            String attachments = Objects.isNull(allByCompanyCode.getAttachmentCodes()) ?
                    attachmentCode : allByCompanyCode.getAttachmentCodes() + "," + attachmentCode;
            allByCompanyCode.setAttachmentCodes(attachments);
            companyRepo.save(allByCompanyCode);
        } else {
            //获取旧附件地址
            UserDbo allByUserName = userRepo.findAllByUserName(code);
            String filePath = allByUserName.getAttachmentCode();
            if (!Objects.isNull(filePath) && !filePath.equals("")){
                //清理旧附件
                AttachmentDbo allByAttachmentCode = attachmentRepo.findAllByAttachmentCode(filePath);
                FileUtils.deleteFile(filePath);
                attachmentRepo.delete(allByAttachmentCode.getId());
            }
            allByUserName.setAttachmentCode(attachmentCode);
            //保存新附件
            userRepo.save(allByUserName);
        }
    }

    @Override
    @Transactional
    public Resource loadAsResource(String attachmentCode) {
        AttachmentDbo allByAttachmentCode = attachmentRepo.findAllByAttachmentCode(attachmentCode);
        return new FileSystemResource(allByAttachmentCode.getFilePath());
    }

    @Override
    @Transactional
    public void deleteFile(String type, String code, String attachmentCode) throws Exception {
        AttachmentDbo allByAttachmentCode = attachmentRepo.findAllByAttachmentCode(attachmentCode);
        if (Objects.isNull(allByAttachmentCode))
            return;
        FileUtils.deleteFile(allByAttachmentCode.getFilePath());
        if (COMPANY_TYPE.equals(type)) {
            CompanyDbo allByCompanyCode = companyRepo.findAllByCompanyCode(code);
            String[] split = allByCompanyCode.getAttachmentCodes().split(",");
            List<String> strings = Arrays.asList(split);
            strings.remove(attachmentCode);
            allByCompanyCode.setAttachmentCodes(strings.toString());
            companyRepo.save(allByCompanyCode);
        } else {
            UserDbo allByUserName = userRepo.findAllByUserName(code);
            allByUserName.setAttachmentCode("");
            userRepo.save(allByUserName);
        }
    }
}
